<?php

namespace App\Modules\Mq\Tasks;

use App\Modules\Mq\Services\PushService;

abstract class TaskAbstract
{
    /**
     * 业务处理入口
     * @param array $body 业务数据体
     * @return bool
     */
    abstract function process(array $data): bool;

    /**
     * 写入MQ
     * @param $data array 业务数据体
     * @param $delayTime int 延时执行时间（毫秒）
     * @return void
     */
    public static function push(array $data, int $delayTime = 0): bool
    {
        $taskname = self::getCalledClassName();
        $create = [
            'task' => $taskname, //业务名称(Task子类名)
            'data' => $data //业务数据体
        ];
        $queueType = empty($delayTime) ? 'common' : 'delayed'; //写入同步队列或延时队列
        return PushService::push($create, $queueType, $delayTime);
    }

    /**
     * 读取子类的类名字
     * 例如："\App\Modules\Mq\Tasks\CoupleTask" 将会转换为 "couple"
     *
     * @return string
     */
    public static function getCalledClassName(): string
    {
        $taskarr = explode('\\', get_called_class());
        return lcfirst(substr($taskarr[count($taskarr) - 1], 0, -4));
    }

    /**
     * 写日志
     * @return string
     */
    public static function addLog($desc, $body = [], $extra = []): void
    {
        $className = self::getCalledClassName();
        $isCli = isCli() ? '-cli' : '';
        write_log("MQHandler" . $isCli, "MQHandler $className $desc", ['body' => $body, 'extra' => $extra]);
    }
}